package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"mei-admin/meirpc/internal/svc"
	"mei-admin/meirpc/meirpc"
	"mei-admin/models/cache"
	"mei-admin/models/mysql"
	"mei-admin/pkg"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *meirpc.LoginRequest) (*meirpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var dataUser mysql.MeiUser
	mysql.DB.Debug().Where("account = ?" + in.Account).Find(dataUser)

	if dataUser.ID != 0 {
		return nil, fmt.Errorf("手机号未注册，请先去注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.CaptchaCode != result {
		return nil, fmt.Errorf("图形验证码错误")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSmsCode != s {
		return nil, errors.New("短信验证码错误")
	}

	if dataUser.Password != pkg.Md5str(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}

	return &meirpc.LoginResponse{
		UserId: int64(dataUser.ID),
	}, nil
}
